package it.koutifaris.testforclassutils;

public class ConsistentNameAssert {

	private static final String TEST_SUFFIX = "Test";
	private static final StackTraceHelper stackTraceHelper = new StackTraceHelper(ConsistentNameAssert.class.getPackage());

	public static void assertConsistentName(Class<?> classUnderTest, Class<?> testClass) {
		assertConsistentName(classUnderTest, testClass.getName());
	}

	public static void assertConsistentName(Class<?> classUnderTest) {
		assertConsistentName(classUnderTest, getCallingClassName());
	}

	private static String getCallingClassName() {
		return stackTraceHelper.getCallingClassName();
	}

	private static void assertConsistentName(Class<?> classUnderTest, String testClassName) {
		assertCompatible(classUnderTest.getName(), testClassName);
	}

	private static void assertCompatible(String classUnderTestName, String testClassName) {
		if (!classUnderTestName.equals(removeTestSuffix(testClassName))) {
			throw new WrongTestClassNameException(classUnderTestName + TEST_SUFFIX, testClassName);
		}
	}

	private static String removeTestSuffix(String name) {
		String result = name;

		int indexOfTest = name.indexOf(TEST_SUFFIX);
		if (indexOfTest >= 0) {
			result = name.substring(0, indexOfTest);
		}

		return result;
	}

}
